#include "scenes/SceneLoading.h"

SceneLoading::SceneLoading( GameApplication& theApp )
   : App( theApp ),
     doneLoading( false ),
     loadingProgress( 0 )
{
	// None
}

void SceneLoading::Initialize()
{
	CreateImageResource( App.GameResources[ "splash loading" ] );
}

void SceneLoading::Terminate()
{
	// None
}

void SceneLoading::Step( gdn::Window& window )
{
	gdn::Event Event;
	while ( window.GetEvent( Event ) )
	{
		if ( Event.type == gdn::Event::WindowClosed )
		{
			App.Close();
		}
	}

	LoadNextResource();
	++loadingProgress;

	if ( doneLoading )
	{
		App.SetActiveScene( "Splash" );
	}
}

void SceneLoading::Draw( gdn::Window& window )
{
	window.Clear();

	gdn::Sprite sprite;
	sprite.SetImage( *App.Images.GetResource(  App.GameResources[ "splash loading" ] ) );

	window.Draw( sprite );

	window.Display();
}

void SceneLoading::LoadNextResource()
{
	std::map< std::string, std::string > resourceList = App.GameResources.GetResourceList();
	if ( loadingProgress == resourceList.size() )
	{
		doneLoading = true;
		return;
	}

	std::map< std::string, std::string >::iterator curRes = resourceList.begin();
	for ( size_t i = 0; i < loadingProgress; ++i, ++curRes );

	if ( curRes->first == "splash loading" )
	{
		++loadingProgress;
		LoadNextResource();
		return;
	}

	std::string resPath = curRes->second;
	std::string resExt  = resPath.substr( resPath.find_last_of( '.' ) + 1 );

	std::cout << curRes->first << " ie. " << resPath << std::endl;
	if ( resExt == "png" or resExt == "jpg" or resExt == "jpg" or resExt == "bmp" )
	{
		CreateImageResource( resPath );
		//std::cout<<"img"<<std::endl;
	}
	else if ( resExt == "ttf" )
	{
		CreateFontResource( resPath );
		//std::cout<<"fnt"<<std::endl;
	}

}

void SceneLoading::CreateImageResource( const std::string& resource )
{
	App.Images.AddResource( resource );
	App.Images.Load( resource );
}

void SceneLoading::CreateFontResource( const std::string& resource )
{
	App.Fonts.AddResource( resource );
	App.Fonts.Load( resource );
}

void SceneLoading::CreateSoundResource( const std::string& resource )
{
	App.Sounds.AddResource( resource );
	App.Sounds.Load( resource );
}

/*
void SceneLoading::CreateMusicResource( const std::string& resource )
{
	App.Music.AddResource( resource );
	App.Music.Load( resource );
}
*/
